<template>
  <n-card :bordered="false" class="proCard">
    <!-- <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm> -->
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="addTable">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建
        </n-button>
      </template>

      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="位置名称" path="siteName">
          <n-input placeholder="请输入位置名称" v-model:value="formParams.siteName" />
        </n-form-item>
        <n-form-item label="位置编码" path="siteCode">
          <n-input placeholder="请输入位置编码" v-model:value="formParams.siteCode" />
        </n-form-item>
        <!-- <n-form-item label="创建时间" path="createTime">
          <n-input placeholder="请输入创建时间" v-model:value="formParams.createTime" />
        </n-form-item> -->
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
    <n-modal
      v-model:show="showSelectBlindBoxModal"
      :show-icon="false"
      preset="dialog"
      title="选择展示盲盒商品"
    >
      <!-- 选择盲盒弹出框子组件 -->
      <BasicSelectBlindBox
        :page-size="5"
        :selected="blindBoxSelectId"
        @update:complete="handleSelectComplete"
      />
      <n-data-table :columns="blindBoxColumns" :data="blindBoxSelectValue" />
      <template #action>
        <n-space>
          <n-button @click="() => (showSelectBlindBoxModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmSelectBlindBox">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { useDialog, NButton, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import BasicSelectBlindBox from '@/components/Shop/SelectBlindBox/BasicSelectBlindBox.vue';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import {
    getHomeSitePage,
    saveSelectBlindBox,
    saveHomeSite,
    updateHomeSite,
    deleteHomeSite,
    getSelectBlindBox,
  } from '@/api/site/homeSite';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { ResultEnum } from '@/enums/httpEnum';

  const rules = {
    siteName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入位置名称',
    },
    siteCode: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入位置编码',
    },
    createTime: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入创建时间',
    },
  };

  const schemas: FormSchema[] = [
    {
      field: 'siteName',
      component: 'NInput',
      label: '位置名称',
      rules: [{ required: false }],
    },
    {
      field: 'siteCode',
      component: 'NInput',
      label: '位置编码',
      rules: [{ required: false }],
    },
    {
      field: 'createTime',
      component: 'NInput',
      label: '创建时间',
      rules: [{ required: false }],
    },
  ];

  const blindBoxColumns = [
    {
      title: 'ID',
      key: 'id',
      width: 50,
    },
    {
      title: '盲盒名称',
      key: 'blindBoxName',
      width: 150,
    },
    {
      title: '价格',
      key: 'price',
      width: 70,
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h(
          NButton,
          {
            size: 'small',
            onClick: () => handleDelSelectBlindBox(row),
          },
          { default: () => '删除' }
        );
      },
    },
  ];

  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();
  // 选择盲盒组件相关参数
  const blindBoxSelectValue = ref<object[]>([]);
  const blindBoxSelectId = ref<number[]>([]);
  //const selectBlindBox = ref<InstanceType<typeof BasicSelectBlindBox>>();

  const showModal = ref(false);
  const showSelectBlindBoxModal = ref(false);
  const formBtnLoading = ref(false);
  const checkedHomeSiteId = ref(); //当前编辑id
  const isEdit = ref(false); // 弹出框是否为编辑
  const editTitle = ref('');
  const dialog = useDialog();
  const formParams = reactive({
    id: 0,
    siteName: '',
    siteCode: '',
    createTime: 0,
  });
  const formParamsBak = { ...formParams };

  const params = ref({});

  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',

        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '选择展示盲盒',
            onClick: handleShowSelectBlindBox.bind(null, record),
          },
          {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
          },
        ],
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 100,
    schemas,
  });

  function addTable() {
    // 新增清空表单
    Object.assign(formParams, formParamsBak);
    isEdit.value = false;
    showModal.value = true;
    editTitle.value = '新建';
  }

  const loadDataTable = async (res) => {
    return await getHomeSitePage({ ...params.value, ...res });
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        let response;
        // 如果是编辑
        if (isEdit.value) {
          formParams.id = checkedHomeSiteId.value;
          response = await updateHomeSite(formParams);
        } else {
          response = await saveHomeSite(formParams);
        }
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          Object.assign(formParams, formParamsBak);
          showModal.value = false;
          reloadTable();
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    checkedHomeSiteId.value = record.id;
    Object.assign(formParams, record);
    editTitle.value = '编辑';
    showModal.value = true;
    isEdit.value = true;
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.info({
      title: '提示',
      content: `您确定想删除吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const params = { id: record.id };
        const response = await deleteHomeSite(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          reloadTable();
        } else {
          message.error(msg);
        }
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
  }

  // 选择展示盲盒点击事件
  function handleShowSelectBlindBox(record: Recordable) {
    checkedHomeSiteId.value = record.id;
    Object.assign(formParams, record);
    console.log('点击了选择展示盲盒', record);
    getSelectBlindBox({ siteCode: record.siteCode }).then((res) => {
      console.log(res);
      if (res) { // 如果有数据
        blindBoxSelectId.value = res.map((item) => item['id']);
        blindBoxSelectValue.value = res;
      }
      
      showSelectBlindBoxModal.value = true;
    });
    
    //selectBlindBox.value?.selectGoods();
  }
  // 弹出框 内删除选中的盲盒
  function handleDelSelectBlindBox(record: Recordable) {
    console.log('删除盲盒');
    blindBoxSelectId.value = blindBoxSelectId.value.filter((item) => item != record.id);
    blindBoxSelectValue.value = blindBoxSelectValue.value.filter((item) => item['id'] != record.id);
  }


  function confirmSelectBlindBox() {
    console.log('确定选择盲盒');
    saveSelectBlindBox({ ...formParams, blindBoxList: blindBoxSelectValue.value }).then(
      (res) => {
        const { message: msg, code } = res;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          showSelectBlindBoxModal.value = false;
        } else {
          message.error(msg);
        }
      }
    );
  }
  // 选择盲盒组件 选择完成事件
  function handleSelectComplete(blindBoxList: object[]) {
    console.log(blindBoxList, '新增部分');
    blindBoxList.forEach((item) => {
      blindBoxSelectValue.value.push(item);
      blindBoxSelectId.value.push(item['id']);
    });
    console.log(blindBoxSelectValue.value, '选择完成');
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    params.value = values;
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }
</script>

<style lang="less" scoped></style>
